package pers.twm.mybatis.util;

import com.intellij.openapi.util.text.StringUtil;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static pers.twm.mybatis.util.ParameterFormatUtil.formatVal;

/**
 * @ClassName SqlUtil
 * @Description TODO
 * @Author tianwanming
 * @Date 2023/3/2 22:48
 * @Version 1.0
 */
public class SqlUtil {

    private static final char SQL_MARK = '?';

    public static String populateSql( String sqlLine,String sqlParameter ) {

        return parseParameterAndAssign(sqlLine, sqlParameter);
    }

    /**
     * 解析参数
     * @Author twm
     * @Date 2023/3/9 22:53
     * @Param
     * @return java.util.List<java.lang.String>
     **/
    private static String parseParameterAndAssign(String sqlLine, String sqlParameter) {

        List<String> parameterList = Arrays.stream(sqlParameter.split(",")).collect(Collectors.toList());

        StringBuilder sqlBuilder = new StringBuilder();

        if(StringUtil.isEmpty(sqlLine)) {
            return "";
        }

        char[] sqlChars = sqlLine.toCharArray();
        int parameterIndex = 0;

        for (int i = 0; i < sqlChars.length; i++) {
            if(SQL_MARK == sqlChars[i]) {
                String parameterVal = parameterList.get(parameterIndex);
                sqlBuilder.append("'"+formatVal(parameterVal)+"'");
                ++parameterIndex;
                continue;
            }
            sqlBuilder.append(sqlChars[i]);
        }

        return sqlBuilder.toString();
    }
}
